package com.sport.facilities.booking.system;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.sport.facilities.booking.db.DatabaseHelper;
import com.sport.facilities.booking.encryption.EncodeDecodeAES;
import com.sport.facilities.booking.system.AlarmReceiver;
import com.sport.facilities.booking.system.httptask.LoginResultTask;
import com.sport.facilities.booking.system.httptask.OnTaskCompleted;
import com.sport.facilities.booking.system.model.Booking;
import com.sport.facilities.booking.system.model.Friend;
import com.sport.facilities.booking.system.model.UserInfo;
import com.sport.facilities.booking.system.ui.DialogHelper;

public class LoginActivity extends ControlActivity {
	private static final String TAG = "LoginActivity";
	private boolean isFirstLoad = true;

	private CheckBox cbRememberme;

	public static final String PREFS_NAME = "MyPrefsFile";
	private static final String PREF_USERNAME = "username";
	private static final String PREF_PASSWORD = "password";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_page);
		detector = new GestureDetector(this);
		
		
		//fnAddAlarm();
		
		
		DatabaseHelper db = new DatabaseHelper(this);

		/**
		 * CRUD Operations
		 * */
		// Inserting temp data for friend list
		// Log.d("Insert: ", "Inserting ..");

		// Friend friend = new Friend();
		// friend.setName("Ken");
		// friend.setEmail("ken@iceberg.com.hk");
		// friend.setPhone("12341234");
		// db.addFriend(friend);

		EditText txt_id = (EditText) findViewById(R.id.text_netid);
		EditText txt_pwd = (EditText) findViewById(R.id.text_pwd);

		
		SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
		String username = pref.getString(PREF_USERNAME, null);
		String password = pref.getString(PREF_PASSWORD, null);

		cbRememberme = (CheckBox) findViewById(R.id.cb_remeber_me);
		// Log.d("----ooooooooooo-----", username + "asdfasdf" + password);

		if ((username != "" && password != "")
				&& (username != null && password != null)) {

			// EncryptDecryptWithDESUsingPassPhrase doencryption = new
			// EncryptDecryptWithDESUsingPassPhrase();
			// String tmpUsr = doencryption.decrypt(""+username);
			// String tmpPwd = doencryption.decrypt(""+password);

			EncodeDecodeAES doDecrypt = new EncodeDecodeAES();

			try {
				String tmpUsr = doDecrypt.decrypt("This is my seed", username);
				String tmpPwd = doDecrypt.decrypt("This is my seed", password);
				
				

				
				txt_id.setText(tmpUsr);
				txt_pwd.setText(tmpPwd);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			cbRememberme.setChecked(true);
		}

		/*
		 * String dateString = "Nov 4, 2003 8:14 PM"; DateFormat format =
		 * DateFormat.getDateTimeInstance( DateFormat.MEDIUM, DateFormat.SHORT);
		 * Calendar cal = Calendar.getInstance();
		 * 
		 * cal.set
		 * 
		 * //Log.d("----ooooooooooo-----", "asdfasdf"); try { DateFormat
		 * dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		 * 
		 * Date date = format.parse(dateString);
		 * 
		 * Log.d("----ooooooooooo-----", );
		 * 
		 * } catch (ParseException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 */
		// fnaddtesttodbandalarm();

		// int randomNumber = (int) (new Date().getTime());
		// Log.d("Alarm Service", "-----------------------"+ randomNumber);

		// setAlarm();

		// DatabaseHelper db = new DatabaseHelper(this);
		// Reading all activity
		// Log.d("Reading: ", "Reading all activity..");
		// List<Booking> booking = db.getAllBooking();

		// for (Booking cn : booking) {
		// String log = "Activity: " + cn.getActivity() + " Type: " +
		// cn.getBkType() + " Centre: "
		// + cn.getCentre() + " Court: " + cn.getCourt() + " Date: "
		// + cn.getDate() + " Time: " + cn.getTime();

		// Writing activity to log

		// Log.d("---------", log);
		// }

		// fngofacebook();

		// TODO: TESTING CODE AND SHOULD BE REMOVED!!
		/*
		 * Button btn = new Button(this); btn.setText("Test Booking");
		 * addContentView(btn, new
		 * ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
		 * ViewGroup.LayoutParams.WRAP_CONTENT)); btn.setOnClickListener(new
		 * MyOnClickListener(1));
		 */
	}

	/*
	 * public void fnaddtesttodbandalarm(){
	 * 
	 * Log.d("Alarm Service", "asfasdfasdf"); //seting tmp bkdetail data Booking
	 * bkdetail = new Booking(); bkdetail.setActivity("Table tennis");
	 * bkdetail.setBkType("Booking Made"); bkdetail.setCentre("SHAWSPORTS");
	 * bkdetail.setCourt("TT1"); bkdetail.setDate("25-Feb-2013");
	 * bkdetail.setTime("03:31-09:29");
	 * 
	 * int randomNumber = (int) (new Date().getTime());
	 * 
	 * String splitdate[] = bkdetail.getDate().split("-");
	 * 
	 * 
	 * Date date = null; try { date = new SimpleDateFormat("MMM",
	 * Locale.ENGLISH).parse(splitdate[1]); } catch (ParseException e) { // TODO
	 * Auto-generated catch block e.printStackTrace(); } Calendar cals =
	 * Calendar.getInstance(); cals.setTime(date); int month =
	 * cals.get(Calendar.MONTH);
	 * 
	 * 
	 * Calendar cal = Calendar.getInstance(); // for using this you need to //
	 * import java.util.Calendar;
	 * 
	 * // add minutes to the calendar object cal.set(Calendar.MONTH, month);
	 * //0=Jan 1=Feb 2=Mar etc..... cal.set(Calendar.YEAR,
	 * Integer.parseInt(splitdate[2])); cal.set(Calendar.DAY_OF_MONTH,
	 * Integer.parseInt(splitdate[0])); cal.set(Calendar.HOUR_OF_DAY,
	 * Integer.parseInt(bkdetail.getTime().substring(0, 2)));
	 * cal.set(Calendar.MINUTE, Integer.parseInt(bkdetail.getTime().substring(3,
	 * 5)));
	 * 
	 * Log.d("Alarm Service", Integer.parseInt(splitdate[0]) + "-" + month + "-"
	 * + Integer.parseInt(splitdate[2]) + " Time:" +
	 * Integer.parseInt(bkdetail.getTime().substring(0, 2)) + ":" +
	 * Integer.parseInt(bkdetail.getTime().substring(3, 5)));
	 * //cal.add(Calendar.SECOND, 5);
	 * 
	 * Intent alarmintent = new Intent(getApplicationContext(),
	 * AlarmReceiver.class); alarmintent.putExtra("title",
	 * "Polyu Sport Facilities Booking System"); alarmintent.putExtra("note",
	 * bkdetail.getActivity() + " Notification");
	 * 
	 * int alarmservice_Id = randomNumber;
	 * 
	 * PendingIntent sender = PendingIntent.getBroadcast(
	 * getApplicationContext(), alarmservice_Id, alarmintent,
	 * PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
	 * 
	 * 
	 * //PendingIntent pIntent =
	 * PendingIntent.getBroadcast(getApplicationContext(), (int) alarm_id,
	 * alarmintent, PendingIntent.FLAG_CANCEL_CURRENT);
	 * 
	 * AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
	 * am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
	 * 
	 * 
	 * DatabaseHelper db = new DatabaseHelper(this);
	 * 
	 * /** CRUD Operations
	 */
	// Inserting activity
	// Log.d("Insert: ", "Inserting ..");
	// db.addActivity(new Booking(bkdetail.getActivity(),bkdetail.getBkType(),
	// bkdetail.getCentre(),
	// bkdetail.getCourt(), bkdetail.getDate(), bkdetail.getTime(),
	// alarmservice_Id));
	// }
	// */

	/*
	 * public void setAlarm() {
	 * 
	 * Log.d("Alarm Service", "setting alarm alarm alarm.."); Calendar cal =
	 * Calendar.getInstance(); // for using this you need to // import
	 * java.util.Calendar;
	 * 
	 * // add minutes to the calendar object cal.set(Calendar.MONTH, 1); //0=Jan
	 * 1=Feb 2=Mar etc..... cal.set(Calendar.YEAR, 2013);
	 * cal.set(Calendar.DAY_OF_MONTH, 23); cal.set(Calendar.HOUR_OF_DAY, 15);
	 * cal.set(Calendar.MINUTE, 38);
	 * 
	 * //cal.add(Calendar.SECOND, 5);
	 * 
	 * Intent alarmintent = new Intent(getApplicationContext(),
	 * AlarmReceiver.class); alarmintent.putExtra("title",
	 * "Polyu Sport Facilities Booking System"); alarmintent.putExtra("note",
	 * "Description of our  Notification");
	 * 
	 * int HELLO_ID = 5555;
	 * 
	 * PendingIntent sender = PendingIntent.getBroadcast(
	 * getApplicationContext(), HELLO_ID, alarmintent,
	 * PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
	 * 
	 * 
	 * //PendingIntent pIntent =
	 * PendingIntent.getBroadcast(getApplicationContext(), (int) alarm_id,
	 * alarmintent, PendingIntent.FLAG_CANCEL_CURRENT);
	 * 
	 * AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
	 * am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
	 * 
	 * }
	 */

	/*
	 * public void fngofacebook(){
	 * 
	 * YesAction yesAction = new YesAction() { public void fnDoYesAction() {
	 * 
	 * Context ctx = getBaseContext(); Intent i = new Intent(ctx,
	 * FacebookActivity.class); final Booking bkdetail = new Booking();
	 * bkdetail.setBkType("Testing Type");
	 * bkdetail.setActivity("Testing Activity");
	 * bkdetail.setCentre("Testing Centre"); bkdetail.setCourt("Testing Court");
	 * bkdetail.setDate("Testing Date"); bkdetail.setTime("Testing Time");
	 * i.putExtra("bookObj", bkdetail); startActivity(i); } };
	 * 
	 * // alert box share box DialogHelper .getYesNoDialog( this,
	 * "Share Booking", "Share this action in FACEBOOK?", yesAction) .show();
	 * 
	 * }
	 */
	
	

	public void fnAddAlarm(){
		
		//Log.d("Alarm Service", "asfasdfasdf");
		//seting tmp bkdetail data
		Booking bkdetail = new Booking();
		bkdetail.setActivity("Table tennis");
		bkdetail.setBkType("Booking Made");
		bkdetail.setCentre("SHAWSPORTS");
		bkdetail.setCourt("TT1");
		bkdetail.setDate("08-May-2013");
		bkdetail.setTime("01:00-02:00");
		
		int randomNumber = (int) (new Date().getTime());				
		
		String splitdate[] = bkdetail.getDate().split("-"); 
		
		
		Date date = null;
		try {
			date = new SimpleDateFormat("MMM", Locale.ENGLISH).parse(splitdate[1]);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    Calendar cals = Calendar.getInstance();
	    cals.setTime(date);
	    int month = cals.get(Calendar.MONTH);
		
		
		Calendar cal = Calendar.getInstance(); // for using this you need to
												// import java.util.Calendar;

		// add minutes to the calendar object
		cal.set(Calendar.MONTH, month); //0=Jan 1=Feb 2=Mar etc.....
		cal.set(Calendar.YEAR, Integer.parseInt(splitdate[2]));
		cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(splitdate[0]));
		cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(bkdetail.getTime().substring(0, 2)));
		cal.set(Calendar.MINUTE, Integer.parseInt(bkdetail.getTime().substring(3, 5)));
		cal.add(Calendar.MINUTE, -5);

		int alarmservice_Id = randomNumber;
		
		Log.d("Setting Alarm Service",  "Alarm ID: "+ alarmservice_Id + "---------" + Integer.parseInt(splitdate[0]) + "-" + month + "-" + Integer.parseInt(splitdate[2]) + " Time:" + Integer.parseInt(bkdetail.getTime().substring(0, 2)) + ":" + Integer.parseInt(bkdetail.getTime().substring(3, 5)));
		//cal.add(Calendar.SECOND, 5);     

		Intent alarmintent = new Intent(getApplicationContext(),
				AlarmReceiver.class);
		alarmintent.putExtra("title", "Polyu Sport Facilities Booking System");
		alarmintent.putExtra("note", bkdetail.getActivity() + " Notification");

		
		PendingIntent sender = PendingIntent.getBroadcast(
				getApplicationContext(), alarmservice_Id, alarmintent,
				PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);

		
		//PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(), (int) alarm_id, alarmintent, PendingIntent.FLAG_CANCEL_CURRENT);
		
		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
		
	}
	
	
	
	
	public void submit(View view) throws Exception {

		EditText txt_id = (EditText) findViewById(R.id.text_netid);
		EditText txt_pwd = (EditText) findViewById(R.id.text_pwd);
		String txt_id_check = txt_id.getText().toString();
		String txt_pwd_check = txt_pwd.getText().toString();
		
		if (!txt_id_check.matches("") && !txt_pwd_check.matches("")) {

			cbRememberme = (CheckBox) findViewById(R.id.cb_remeber_me);

			if (cbRememberme.isChecked()) {

				// String tempUsr = doencryption.encrypt(""+txt_id.getText());
				// String tempPwd = doencryption.encrypt(""+txt_pwd.getText());

				EncodeDecodeAES doEncrypt = new EncodeDecodeAES();

				String tempUsr = doEncrypt.encrypt("This is my seed", txt_id
						.getText().toString());
				String tempPwd = doEncrypt.encrypt("This is my seed", txt_pwd
						.getText().toString());

				Log.d("----encryption-----", tempUsr + "---------------------"
						+ tempPwd);

				getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
						.putString(PREF_USERNAME, "" + tempUsr)
						.putString(PREF_PASSWORD, "" + tempPwd).commit();
			} else {

				getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
						.putString(PREF_USERNAME, "")
						.putString(PREF_PASSWORD, "").commit();
			}

			final Activity mainActivity = this;
			UserInfo uInfo = fnGetUserInfo();
			OnTaskCompleted completeAction = new OnTaskCompleted() {
				public void onTaskCompleted(Object s) {
					Toast.makeText(mainActivity, "Login Successfuly",
							Toast.LENGTH_LONG).show();
					Intent myIntent = new Intent(LoginActivity.this,
							MainActivity.class);
					LoginActivity.this.startActivity(myIntent);
				}

				public void onTaskFailed(String errMessage) {
					Log.e(TAG, errMessage);
					DialogHelper.getOkAlertDialog(mainActivity,
							"Error While Login", errMessage).show();
				}
			};
			LoginResultTask pc = new LoginResultTask(this, uInfo,
					completeAction);
			pc.fnLogin();

		}

	}

	public void cancel(View view) {
		EditText txt_id = (EditText) findViewById(R.id.text_netid);
		EditText txt_pwd = (EditText) findViewById(R.id.text_pwd);
		CheckBox rmb_chk = (CheckBox) findViewById(R.id.cb_remeber_me);
		
		
		txt_id.setText("");
		txt_pwd.setText("");
		rmb_chk.setChecked(false);
		
		txt_id.clearComposingText();
		txt_pwd.clearComposingText();
	}

	private UserInfo fnGetUserInfo() {
		EditText txt_id = (EditText) findViewById(R.id.text_netid);
		EditText txt_pwd = (EditText) findViewById(R.id.text_pwd);
		RadioGroup user_type = (RadioGroup) findViewById(R.id.user_type);
		CheckBox remeber = (CheckBox) findViewById(R.id.cb_remeber_me);

		UserInfo i = new UserInfo();
		i.setName(txt_id.getText().toString());
		i.setPass(txt_pwd.getText().toString());
		i.setRemeber(remeber.isChecked());
		if (user_type.getCheckedRadioButtonId() == R.id.user_type1) {
			i.setUserType(1);// Student/Staff
		} else if (user_type.getCheckedRadioButtonId() == R.id.user_type2) {
			i.setUserType(2);// Other
		}
		return i;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Log.d(TAG, "onCreateOptionsMenu");
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public boolean onMenuItemSelected(int menuId, MenuItem item) {
		Log.d(TAG, "onMenuItemSelected : " + item.getItemId());
		switch (item.getItemId()) {
		case R.id.menu_settings:
			Toast.makeText(this, "Setting Menu Clicked", Toast.LENGTH_LONG)
					.show();
			return true;
		}
		return false;
	}

	@Override
	public void onResume() {
		super.onResume();
		if (isFirstLoad == true) {
			fnLoadLoginPage();
			isFirstLoad = false;
		}
	}

	private void fnLoadLoginPage() {
		/*
		 * Pretend to load the login page before sending out login action So
		 * that server log will log like human action.
		 */
		final Activity mainActivity = this;
		OnTaskCompleted completeAction = new OnTaskCompleted() {
			public void onTaskCompleted(Object s) {
				Log.e(TAG, "Web page loaded successfully.");
			}

			public void onTaskFailed(String errMessage) {
				Log.e(TAG, errMessage);
				DialogHelper.getOkAlertDialog(mainActivity, "Error Fail",
						errMessage).show();
			}
		};
		LoginResultTask pc = new LoginResultTask(this, new UserInfo(),
				completeAction);
		pc.fnLoadLoginPage();
	}

}
